package com.tengfei.main.user.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tengfei.common.constant.Constants;
import com.tengfei.common.constant.UserConstants;
import com.tengfei.common.core.service.LogininforService;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.common.exception.user.CaptchaException;
import com.tengfei.common.exception.user.CaptchaExpireException;
import com.tengfei.common.utils.ServletUtils;
import com.tengfei.common.utils.StringUtils;
import com.tengfei.common.utils.redis.RedisUtils;
import com.tengfei.main.system.domain.SysDept;
import com.tengfei.main.system.domain.SysUser;
import com.tengfei.main.system.mapper.SysDeptMapper;
import com.tengfei.main.system.service.ISysUserService;
import com.tengfei.main.user.domain.bo.login.UserRegisterBo;
import com.tengfei.main.user.service.IUserLoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feige
 * @version v1.0
 * @date 2022-08-14-15:12
 * @description
 */

@Service
public class UserLoginServiceImpl implements IUserLoginService {

    @Resource
    private ISysUserService userService;
    @Resource
    private LogininforService asyncService;
    @Resource
    private SysDeptMapper deptMapper;

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public void register(UserRegisterBo user) {
        HttpServletRequest request = ServletUtils.getRequest();
        String username = user.getUsername();
        String password = user.getPassword();
        String phoneNumber = user.getPhoneNumber();
        // 判断验证码
        validateCaptcha(username, user.getCode(), user.getUuid(), request);
        // 判断用户名
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            throw new ServiceException("用户名存在");
        }
        // 判断手机号
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(phoneNumber))) {
            throw new ServiceException("手机号已注册");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setName(user.getName());
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setDeptId(user.getDeptId());
        sysUser.setUserType("sys_user");
        sysUser.setPhonenumber(phoneNumber);
        boolean regFlag = userService.registerUser(sysUser);
        if (!regFlag) {
            throw new ServiceException("用户注册失败");
        }
        asyncService.recordLogininfor(username, Constants.REGISTER, "用户注册成功", request);

    }

    /**
     * 获取部门简要信息
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getDeptList() {
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(SysDept::getParentId)
                .orderByAsc(SysDept::getOrderNum);
        List<SysDept> sysDepts = deptMapper.selectList(lqw);
        List<Map<String, Object>> deptSimpleInfo = new ArrayList<>();
        sysDepts.forEach(sysDept -> {
            Map<String, Object> map = new HashMap<>();
            map.put("deptId", sysDept.getDeptId());
            map.put("deptName", sysDept.getDeptName());
            map.put("parentId", sysDept.getParentId());
            deptSimpleInfo.add(map);
        });
        return deptSimpleInfo;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid, HttpServletRequest request) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            asyncService.recordLogininfor(username, Constants.REGISTER, "验证码为空", request);
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            asyncService.recordLogininfor(username, Constants.REGISTER, "验证码错误", request);
            throw new CaptchaException();
        }
    }
}
